using UnityEngine;
using System.Collections;

public class MyPlayer : MonoBehaviour {

	//Vector2 lastPosition;
	Vector3 hitPoint;
	public float PlayerSpeed;
	float offset=9.0f;
	// Use this for initialization
	// Update is called once per frame
	
	void FixedUpdate(){
		
		transform.rigidbody.velocity = new Vector3(0, 0, 0);
		
		float amtToMoveY = Input.GetAxisRaw("Mouse Y") * PlayerSpeed;
		float amtToMoveX = Input.GetAxisRaw("Mouse X") * PlayerSpeed;
		
		
		if(Check(amtToMoveX, amtToMoveY))
		{
			transform.Translate(Vector3.up * amtToMoveX);
			transform.Translate(Vector3.right * amtToMoveY);
		}
		else
		{
			
		}
		
		//lastPosition = Input.mousePosition;
	}
	
	bool Check(float x, float y){
		RaycastHit hitCenter;
		RaycastHit hitRight;
		RaycastHit hitLeft;
		bool hit=false;
		
		Vector3 crash = new Vector3(x, y, 0);
		Vector3 pos = this.transform.position;
		
		if(Physics.Raycast(new Vector3(pos.x, pos.y, pos.z), crash, out hitCenter, crash.magnitude))
		{
			hit=true;
		}
		if(Physics.Raycast(new Vector3(pos.x + offset, pos.y, pos.z), crash, out hitRight, crash.magnitude))
		{
			hit=true;
		}
		if(Physics.Raycast(new Vector3(pos.x - offset, pos.y, pos.z), crash, out hitLeft, crash.magnitude))
		{
			hit=true;
		}
		
		//Physics.Raycast(new Vector3(pos.x, pos.y, pos.z), crash, out hitCenter, crash.magnitude);
		//Physics.Raycast(new Vector3(pos.x + offset, pos.y, pos.z), crash, out hitRight, crash.magnitude);
		//Physics.Raycast(new Vector3(pos.x - offset, pos.y, pos.z), crash, out hitLeft, crash.magnitude);
		
		if(hit)
		{
		RaycastHit hitClosest = ClosestHit(hitLeft, hitRight, hitCenter);
		/*if(hitClosest.point==new Vector3(0,0,0))
			{
			transform.position = hitClosest.point;
			}*/
		}
		return !hit;
	}
	
	void Update () {
	

		
	}
	
	void OnDrawGizmos()
	{
		if(hitPoint != null)
			Gizmos.DrawWireSphere(hitPoint, 0.5f);
	}
	
	RaycastHit ClosestHit(RaycastHit y, RaycastHit x, RaycastHit z)
	{
		if(x.distance==0)
			x.distance=100000;
		if(y.distance==0)
			y.distance=100000;
		if(z.distance==0)
			z.distance=100000;
		
		if(x.distance<=y.distance)
		{
			if(x.distance<=z.distance)
			{
				return x;
			}
			else
			{
				return z;
			}
		}
		else
		{
			if(y.distance<=z.distance)
			{
				return y;
			}
			else
			{
				return z;
			}
		}
	}
}
